<template>
      <div class="app-body">
            <!-- 条件查询 -->
            <el-col :span="24" class="info-search-box">
                  <div class="search">
                        <div class="search-item">
                              编号 :
                              <el-input
                                    size="mini"
                                    v-model="search.id"
                                    placeholder="通过编号查询"
                                    clearable
                              ></el-input>
                        </div>
                        <div class="search-item">
                              书籍名称 :
                              <el-input
                                    size="mini"
                                    v-model="search.goodsName"
                                    placeholder="通过书籍名称查询"
                                    clearable
                              ></el-input>
                        </div>
                        <div class="search-item">
                              分类 :
                              <el-select v-model="search.classify" placeholder="请选择" size="mini">
                                    <el-option
                                          v-for="item in classify"
                                          :key="item.id"
                                          :label="item.name"
                                          clearable
                                          :value="item.id">
                                    </el-option>
                              </el-select>
                        </div>
                        <div class="search-item">
                              <el-button size="mini" type="primary" @click="toPage">查询</el-button>
                        </div>
                  </div>
            </el-col>
            <el-col :span="24" class="button-box">
                  <el-button size="mini" type="primary" icon="el-icon-plus" @click="add"
                        >新增</el-button
                  >
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="delList"
                        >批量删除</el-button
                  >
                  <el-button size="mini" type="warning" icon="el-icon-upload" @click="inducts"
                        >批量导入</el-button
                  >
            </el-col>
            <el-table
                  @selection-change="handleSelectionChange"
                  size="mini"
                  v-loading="loading"
                  :header-cell-style="$setting.table_header"
                  :stripe="true"
                  :fit="true"
                  :data="tableData"
                  border
                  style="width: 100%"
            >
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column prop="id" label="编号"></el-table-column
                  ><el-table-column
                        prop="createTime"
                        label="创建时间"
                        :formatter="(row) => formatDate(row.createTime)"
                  ></el-table-column
                  ><el-table-column
                        prop="updateTime"
                        label="更新时间"
                        :formatter="(row) => formatDate(row.updateTime)"
                  ></el-table-column
                  >
                  <el-table-column prop="goodsName" label="书籍名称"></el-table-column
                  >
                  <el-table-column prop="goodsPrice" label="书籍价格">
                        <template slot-scope="scope">
                              <el-tag type="success">{{scope.row.goodsPrice}}</el-tag>
                        </template>
                  </el-table-column>
                  <el-table-column prop="classifyName" label="分类">
                        <template slot-scope="scope">
                              <el-tag>{{scope.row.classifyName}}</el-tag>
                        </template>
                  </el-table-column>
                  <el-table-column prop="stock" label="库存"></el-table-column>
                  <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                              <el-button size="mini" type="primary" icon="el-icon-picture-outline" circle @click.native="picture(scope.row)"></el-button>
                              <el-button
                                    size="mini"
                                    type="info"
                                    icon="el-icon-view"
                                    circle
                                    @click.native="show(scope.row)"></el-button>
                              <el-button
                                    size="mini"
                                    type="warning"
                                    icon="el-icon-edit"
                                    circle
                                    @click.native="edit(scope.row)"
                              ></el-button>
                              <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    circle
                                    @click.native="del(scope.row)"
                              ></el-button>
                        </template>
                  </el-table-column>
            </el-table>
            <el-col :span="24">
                  <div class="page-box">
                        <el-pagination
                              @size-change="handleSizeChange"
                              :small="true"
                              :hide-on-single-page="true"
                              @current-change="changePage"
                              background
                              layout="total, sizes, prev, pager, next"
                              :total="total"
                              :page-size="pageSize"
                        ></el-pagination>
                  </div>
            </el-col>
            <!-- 弹出层 -->
            <el-dialog
                  :title="formTitle"
                  :visible.sync="formVisible"
                  top="5vh"
                  width="50%"
                  :before-close="handleClose"
            >
                  <el-form :model="form" :rules="rules" ref="form">
                        <el-form-item
                              label="书籍名称"
                              :label-width="formLabelWidth"
                              prop="goodsName"
                              ><el-input
                                    placeholder="请输入书籍名称"
                                    v-model="form.goodsName"
                                    @change="isChange = true"
                                    size="small"
                              ></el-input></el-form-item
                        ><el-form-item
                              label="书籍价格"
                              :label-width="formLabelWidth"
                              prop="goodsPrice"
                              >
                              <el-input-number v-model="form.goodsPrice" @change="isChange = true"
                                    size="small" :precision="2" :step="0.1" :max="10000"></el-input-number>
                              </el-form-item
                        ><el-form-item label="分类" :label-width="formLabelWidth" prop="classify"
                              >
                              <el-select size="small" v-model="form.classify" placeholder="请选择" @change="isChange = true">
                                    <el-option
                                          v-for="item in classify"
                                          :key="item.id"
                                          :label="item.name"
                                          :value="item.id">
                                    </el-option>
                              </el-select>
                              </el-form-item
                        >
                        <el-form-item label="库存" :label-width="formLabelWidth" prop="stock">
                              <el-input-number size="small" @change="isChange = true" v-model="form.stock" :min="1" :max="500"></el-input-number>
                        </el-form-item>
                        <el-form-item label="描述" :label-width="formLabelWidth" prop="description">
                              <Editor ref="editor" v-model="form.description" @change="isChange = true"></Editor>
                        </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="formVisible = false">取 消</el-button>
                        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
                  </div>
            </el-dialog>
            <el-dialog
                  title="选择数据表格"
                  :visible.sync="inductsVisible"
                  width="40%"
                  :before-close="handleClose"
            >
                  <el-form size="mini">
                        <el-form-item label="选择表格" :label-width="formLabelWidth">
                              <input
                                    type="file"
                                    class="file-left-input"
                                    @change="inductsChange()"
                                    ref="inducts"
                                    multiple
                                    accept=".xls,.xlsx"
                              />
                        </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="inductsVisible = false">取 消</el-button>
                        <el-button size="mini" type="primary" @click="templateDownload"
                              >下载模板</el-button
                        >
                  </div>
            </el-dialog>
            <el-dialog title="书籍图片" v-if="pictureVisible" :visible.sync="pictureVisible" width="60%" :before-close="handleClose">
                  <GoodsImg :goods="form.id" ></GoodsImg>
                  <div slot="footer" class="dialog-footer">
                        <el-button @click="pictureVisible=false">取 消</el-button>
                  </div>
            </el-dialog>
      </div></template
>
<script>
import Editor from '../commons/Editor.vue'
import GoodsImg from './goodsImg.vue'

export default {
      components:{
            Editor,
            GoodsImg
      },
      props: [],
      data() {
            return {
                  loading: true,
                  page: 0,
                  pageSize: 10,
                  total: 0,
                  tableData: [],
                  classify:[],
                  formTitle: "",
                  formVisible: false,
                  inductsVisible: false,
                  pictureVisible:false,
                  form: {
                        id: "",
                        createTime: "",
                        updateTime: "",
                        creator: "",
                        goodsName: "",
                        goodsPrice: "",
                        description: "",
                        classify: "",
                        stock: "",
                  },
                  rules: {
                        id: [{ required: true, message: "请输入编号", trigger: "blur" }],
                        createTime: [
                              { required: true, message: "请输入创建时间", trigger: "blur" },
                        ],
                        updateTime: [
                              { required: true, message: "请输入更新时间", trigger: "blur" },
                        ],
                        creator: [{ required: true, message: "请输入创建人", trigger: "blur" }],
                        goodsName: [{ required: true, message: "请输入书籍名称", trigger: "blur" }],
                        goodsPrice: [
                              { required: true, message: "请输入书籍价格", trigger: "blur" },
                        ],
                        description: [{ required: true, message: "请输入描述", trigger: "blur" }],
                        classify: [{ required: true, message: "请输入分类", trigger: "blur" }],
                        stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
                  },
                  formLabelWidth: "80px",
                  /** 弹出框标签宽度*/ isChange: false,
                  search: { id: "", creator: "", goodsName: "", classify: "" },
                  multipleSelection: [],
                  pageUrlPath: "/client/goods",
            };
      },
      methods: {
            show(row){
                  this.$router.push({
                        path:'/admin/showGoods/'+row.id
                  })
            },
            picture(row){
                  this.form=row;
                  this.pictureVisible=true;
            },
            initClassify(){
                  this.$axios.get(
                              this.$url +
                                    "client/classify/list?page=0&pageSize=100"
                        )
                        .then((response) => {
                              this.classify = response.data.data.list;
                        });
            },
            /**初始化字典 */ initDist() {
                  this.initClassify();
            },
            /**格式化日期 */ formatDate(timeStamp) {
                  let date = new Date(timeStamp);
                  let month =
                        date.getMonth() + 1 < 10
                              ? "0" + (date.getMonth() + 1)
                              : date.getMonth() + 1;
                  let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                  let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                  let minutes =
                        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                  return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes;
            },
            handleSizeChange(size) {
                  this.pageSize = size;
                  this.toPage();
            },
            init() {
                  this.toPage();
                  this.initDist();
            },
            toPage() {
                  this.loading = true;
                  let param = "";
                  Object.keys(this.search).map((key) => {
                        if (this.search[key] != undefined && this.search[key] != "") {
                              param += "&" + key + "=" + this.search[key];
                        }
                  });
                  this.$axios
                        .get(
                              this.$url +
                                    this.pageUrlPath +
                                    "/list?page=" +
                                    this.page +
                                    "&pageSize=" +
                                    this.pageSize +
                                    param
                        )
                        .then((response) => {
                              this.tableData = response.data.data.list;
                              this.total = response.data.data.total;
                              this.loading = false;
                        });
            },
            /**监听页码发生变化 */ changePage(e) {
                  this.page = e - 1;
                  this.toPage();
            },
            add() {
                  this.form = this.$options.data().form;
                  this.formTitle = "新增";
                  this.formVisible = true;
            },
            handleClose(done) {
                  this.$confirm("确认关闭？").then(() => {
                        done();
                  });
            },
            submit() {
                  this.$root.loading = true;
                  let formData = new FormData();
                  Object.keys(this.form).map((key) => {
                        if (key!='img' && this.form[key] != undefined && this.form[key] != "") {
                              formData.append(key, this.form[key]);
                        }
                  });
                  this.$axios({
                        method: "POST",
                        url: this.$url + this.pageUrlPath + "/add",
                        data: formData,
                  }).then((res) => {
                        if (res.data.status.code < 400) {
                              this.toPage();
                              this.formVisible = false;
                        }
                  });
            },
            edit(row) {
                  this.form = row;
                  this.formTitle = "编辑";
                  this.formVisible = true;
            },
            /*删除*/ del(row) {
                  this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                  }).then(() => {
                        this.$root.loading = true;
                        let format = new FormData();
                        format.append("ids", row.id);
                        this.$axios({
                              method: "DELETE",
                              data: format,
                              url: this.$url + this.pageUrlPath + "/del",
                        }).then((res) => {
                              if (res.data.status.code == 200) {
                                    this.toPage();
                              }
                        });
                  });
            },
            /**下载表 */ templateDownload() {
                  window.open(this.$url + this.pageUrlPath + "/template");
            },
            /**批量删除 */ delList() {
                  this.$confirm("此操作将永久删除信息, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                  }).then(() => {
                        this.$root.loading = true;
                        let format = new FormData();
                        this.multipleSelection.forEach((item) => {
                              format.append("ids", item.id);
                        });
                        this.$axios({
                              method: "DELETE",
                              data: format,
                              url: this.$url + this.pageUrlPath + "/del",
                        }).then((res) => {
                              if (res.data.status.code == 200) {
                                    this.toPage();
                              }
                        });
                  });
            },
            /**选择框 val为当前所有选择的内容数组 */ handleSelectionChange(val) {
                  this.multipleSelection = val;
            },
            /**点击批量导入 */ inducts() {
                  this.inductsVisible = true;
            },
            /**选择批量 */ inductsChange() {
                  let files = this.$refs.inducts.files;
                  /*获取选择的文件*/ let len = files.length;
                  /*文件个数*/ if (len != 1) {
                        this.$message({ message: "需要且只能上传一个文件", type: "warning" });
                        return;
                  }
                  let formData = new FormData();
                  formData.append("file", files[0]);
                  this.$axios({
                        method: "post",
                        url: this.$url + this.pageUrlPath + "/inducts",
                        data: formData,
                        headers: { "Content-Type": "multipart/form-data" },
                  })
                        .then((res) => {
                              /*上传成功后是否需要将选择的文件滞空*/ this.$refs.inducts.value = null;
                              if (res.data.status.code == 200) {
                                    this.inductsVisible = false;
                                    this.toPage();
                              }
                        })
                        .catch(() => {
                              this.$refs.inducts.value = null;
                              this.$message({
                                    message: "上传失败，请检查文件合法性！",
                                    type: "error",
                              });
                        });
            },
      },
      mounted() {
            this.init();
      },
};
</script>
<style lang="less" scoped></style>
